import Vue from 'vue'
import Notification from './notify-extend'

const component = Vue.extend(Notification)

let seed = 0
const instances = []

const removeInstance = id => {
    const ind = instances.findIndex( inst => id === inst.id )
    const instance = instances[ind]
    const len = instances.length
    const removeHeight = instance.vm.$el.offsetHeight
    for( let i = ind; i < len; i++ ){
        instances[i].verticalOffset -= ( parseInt(removeHeight) + 16 )
    }
    instances.splice(ind,1)
    document.body.removeChild(instance.vm.$el)
}

const notify = options => {
    const {
        duration,
        ...rest
    } = options

    const instance = new component({
        propsData : {...rest},
        data: { 
            duration : duration === undefined ? 3000 : duration
        }
    })

    const id = `instance_${seed++}`
    instance.id = id
    instance.vm = instance.$mount()
    
    let verticalOffset = 0
    instances.forEach( inst => {
        verticalOffset += inst.vm.$el.offsetHeight + 16
    })
    verticalOffset += 16
    instance.verticalOffset = verticalOffset

    instance.$on('removeInstance',(id) => {
        removeInstance(id)
    })

    instances.push(instance)
    document.body.appendChild(instance.vm.$el)

    return instance.vm
}

export default notify